package service

// pagination.go
// 分页相关的查询

import (
	"fmt"
	"gforum/global"
	"gforum/model"
	"strings"
)

// GetTotalSize get count of model by user id
func GetTotalSize(id string, modelToCount any) (int64, error) {
	var total int64

	var belongsTo string
	switch modelToCount.(type) {
	case *model.Post:
		belongsTo = "author_id"
	case *model.Comment:
		belongsTo = "post_id"
	default:
		panic("unsupported model type")
	}

	err := global.Db.Model(modelToCount).Where(fmt.Sprint(belongsTo, " = ?"), id).Count(&total).Error
	if err != nil {
		return 0, err
	}

	return total, nil
}

// GetTotalPage get count of total page separated by size
func GetTotalPage(size int, total int64) int {
	totalPages := (int64(total) + int64(size) - 1) / int64(size)
	return int(totalPages)
}

// GetTotalCommentSize GetTotalSize 的复用，但是和获取 post 下的所有 comment 撞了， 先这样吧
func GetTotalCommentSize(id string, modelToCount any) (int64, error) {
	var total int64
	err := global.Db.Model(modelToCount).Where("user_id = ?", id).Count(&total).Error
	if err != nil {
		return 0, err
	}

	return total, nil
}

// GetTotalPostsSizeWithTopic 获取指定主题的所有帖子数量
func GetTotalPostsSizeWithTopic(topic string) (total int64, err error) {
	if topic == "all" {
		err = global.Db.Model(&model.Post{}).Count(&total).Error
	} else {
		err = global.Db.Model(&model.Post{}).Where("topic = ?", topic).Count(&total).Error
	}
	if err != nil {
		return 0, err
	}

	return total, nil
}

func GetSearchResultSize(query model.SearchPagination) (int64, error) {
	var total int64

	db := global.Db.Model(&model.Post{})

	if query.Topic != "all" {
		db = db.Where("topic = ?", query.Topic)
	}

	terms := strings.Fields(query.Q)
	for _, term := range terms {
		pat := fmt.Sprintf("%%%s%%", term)
		db = db.Where("(title LIKE ? OR content LIKE ?)", pat, pat)
	}

	if err := db.Count(&total).Error; err != nil {
		return 0, err
	}
	return total, nil
}
